#include "DepthReader.h"
#include <iostream>

using namespace std;


DepthReader::DepthReader(char datafilename[], char metafilename[])
{
	datafile = fopen(datafilename, "rb");
	if (datafile == NULL) {
		cout << "data file open failed." << endl;
	}

	metafile = fopen(metafilename, "r");
	if (metafile == NULL) {
		cout << "meta file open failed." << endl;
	}

	fgets(buf, BUFSIZE, metafile);
	fscanf(metafile, " %d %d\n", &width, &height);
	tmpFrameBuf = new short[width*height];

	parsed = false;
	curRecId = -1;
	curRecClocks = -1;
}

bool DepthReader::getNextRec(void) {
	if (parsed) getNextFrame(tmpFrameBuf);
	parsed = true;
	fgets(buf, BUFSIZE, metafile);
	if (buf[0] == '#') return false;
	sscanf(buf, " %d %d", &curRecId, &curRecClocks);
	return true;
}

bool DepthReader::getNextFrame(short *sptr) {
	if (!parsed)
		if (getNextRec() == false) return false;
	parsed = false;
	fread(sptr, sizeof(short), width*height, datafile);
	return true;
}

DepthReader::~DepthReader(void)
{
	fclose(metafile);
	fclose(datafile);
	delete[] tmpFrameBuf;
}
